package com.example.springsecurity.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;

//此处运用aop编程
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {



    //这个版本的springboot需要将密码加密
    //在spring security5中提供的很多密码的加密方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //一般数据就需要从数据库中取出auth.jdbcAuthentication
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//定义密码加密方式
                .withUser("zyb").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("dwh").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //实现首页能够访问，功能页需要权限
        //*****注意：antMatchers中的字符串为controller映射的名称并非文件夹名
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/toLevel1/**").hasRole("vip1")
                .antMatchers("/toLevel2/**").hasRole("vip2")
                .antMatchers("/toLevel3/**").hasRole("vip3");

        //没有权限默认到另一个页面（一般问登陆页面）他自己会进入到一个自带的login页面
        http.formLogin().loginProcessingUrl("/");
        //注销以及注销设置
        http.logout().logoutSuccessUrl("/");
        //关闭csrf功能，确保安全
        http.csrf().disable();
    }
}
